package config

import (
	"flag"
	"fmt"
	"os"
	"time"
)

type Config struct {
	Host       string
	Port       int
	User       string
	Password   string
	OutputFile string
	Timeout    time.Duration
}

func ParseFlags() (*Config, error) {
	var cfg Config

	flag.StringVar(&cfg.Host, "host", "localhost", "MongoDB主机地址")
	flag.StringVar(&cfg.Host, "h", "localhost", "MongoDB主机地址(简写)")
	flag.IntVar(&cfg.Port, "port", 27017, "MongoDB端口")
	flag.IntVar(&cfg.Port, "P", 27017, "MongoDB端口(简写)")
	flag.StringVar(&cfg.User, "user", "admin", "MongoDB用户名")
	flag.StringVar(&cfg.User, "u", "admin", "MongoDB用户名(简写)")
	flag.StringVar(&cfg.Password, "password", "", "MongoDB密码")
	flag.StringVar(&cfg.Password, "p", "", "MongoDB密码(简写)")
	flag.StringVar(&cfg.OutputFile, "output-file", "mongodb_report.html", "输出文件")
	flag.StringVar(&cfg.OutputFile, "o", "mongodb_report.html", "输出文件(简写)")
	timeout := flag.Int("timeout", 20, "操作超时时间(秒)")
	timeoutShort := flag.Int("t", 20, "操作超时时间(秒)(简写)")
	showHelp := flag.Bool("help", false, "显示帮助信息")

	flag.Parse()

	if *showHelp {
		printHelp()
		os.Exit(0)
	}

	if *timeoutShort != 20 && *timeout == 20 {
		cfg.Timeout = time.Duration(*timeoutShort) * time.Second
	} else {
		cfg.Timeout = time.Duration(*timeout) * time.Second
	}

	if cfg.Host == "" {
		return nil, fmt.Errorf("必须指定主机地址")
	}

	return &cfg, nil
}

func printHelp() {
	fmt.Println("MongoDB巡检工具")
	fmt.Println("用法: mongoscan [参数]")
	fmt.Println()
	fmt.Println("参数:")
	fmt.Println("  --help           \t显示帮助信息")
	fmt.Println("  --host         -h\tMongoDB主机地址")
	fmt.Println("  --port         -P\tMongoDB端口(默认:27017)")
	fmt.Println("  --user         -u\tMongoDB用户名")
	fmt.Println("  --password     -p\tMongoDB密码")
	fmt.Println("  --output-file  -o\t输出文件名(默认:mongodb_report.html)")
	fmt.Println("  --timeout      -t\t操作超时时间(秒，默认:20)")
	fmt.Println()
	fmt.Println("示例:")
	fmt.Println("  mongoscan -h 127.0.0.1 -P 27017 -u admin -p your_password")
}
